<?php
/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2016/12/7
 * Time: 9:33
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Http\Service\PermissionService;
use App\Http\Service\RoleService;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function index(Request $request){
        $request->has('pageSize')?$pageSize=$request->input('pageSize'):$pageSize=20;
        $request->has('searchVal')?$searchVal=$request->input('searchVal'):$searchVal=null;
        $roleList = RoleService::getRoleListPageInit($pageSize,$searchVal);
        return view('admin.role.index',[
            'pageSize'=>$pageSize,
            'searchVal'=>$searchVal,
            'roles'=>$roleList,
        ]);
    }

    public function edit(Request $request){
        $roleId=$request->input('roleId');
        $groupedPermissions=PermissionService::getAllPermissionGroupby();
        $info = RoleService::getOneRoles($roleId);
        return view('admin.role.edit',[
            'info' => $info,
            'Permissions'=>$groupedPermissions,
        ]);
    }

    public function doEdit(Request $request){
        $this->roleValidate($request);
        $roleData=$request->input('info');
        $permissions = $request->input('permissions');
        if(RoleService::updateOneRole($roleData,$permissions)){
            return redirect('/admin/role/index');
        }else{
            return redirect()->back();
        }
    }

    public function create(Request $request){
        $groupedPermissions=PermissionService::getAllPermissionGroupby();
        return view('admin.role.create',[
            'Permissions'=>$groupedPermissions,
        ]);
    }

    public function doCreate(Request $request){
        $this->roleValidate($request);
        $roleData=$request->input('info');
        $permissions = $request->input('permissions');

        if(RoleService::createOneRole($roleData,$permissions)){
            return redirect('/admin/role/index');
        }else{
            return redirect()->back();
        }
    }
    public function delete(Request $request){
        $roleId=$request->input('roleId');
        if(RoleService::deleteOneRole($roleId)){
            return response()->json([
                'code' => 200,
                'message' => '操作成功！'
            ]);
        }
        else{
            return response()->json([
                'code' => 500,
                'message' => '操作失败！请重试!'
            ]);
        }
    }

    private function roleValidate(Request $request){
        return $this->validate($request,[
            'info.name'=>'required',
            'info.label'=>'required',
        ],[
            'required'=>':attribute不能为空',
            'integer'=>':attrbute必须为整数'
        ],[
            'info.name'=>'权限规则',
            'info.label'=>'权限名称',
            'info.description'=>'权限描述',
        ]);
    }
}